/**
 * 任务数据模型
 * 处理任务相关的数据库操作
 */
const { query } = require('../config/database');

const taskModel = {
  /**
   * 获取用户的所有任务
   * @param {number} userId - 用户ID
   * @param {Object} filters - 过滤条件
   * @returns {Promise<Array>} 任务列表
   */
  findAll: async (userId, filters = {}) => {
    // 基础查询
    let sql = `
      SELECT t.*, c.name as category_name, c.color as category_color 
      FROM tasks t
      LEFT JOIN task_categories c ON t.category_id = c.id
      WHERE t.user_id = ?
    `;
    
    const queryParams = [userId];
    
    // 添加筛选条件
    if (filters.status !== undefined) {
      sql += ' AND t.status = ?';
      queryParams.push(filters.status);
    }
    
    if (filters.category_id) {
      sql += ' AND t.category_id = ?';
      queryParams.push(filters.category_id);
    }
    
    // 日期过滤
    if (filters.date) {
      const date = new Date(filters.date);
      const dateStr = date.toISOString().split('T')[0];
      sql += ' AND DATE(t.start_time) = ? OR DATE(t.end_time) = ?';
      queryParams.push(dateStr, dateStr);
    }
    
    // 排序
    sql += ' ORDER BY t.priority DESC, t.created_at DESC';
    
    return await query(sql, queryParams);
  },

  /**
   * 根据ID获取任务
   * @param {number} id - 任务ID
   * @param {number} userId - 用户ID (用于验证任务所有权)
   * @returns {Promise<Object|null>} 任务对象或null
   */
  findById: async (id, userId) => {
    const sql = `
      SELECT t.*, c.name as category_name, c.color as category_color 
      FROM tasks t
      LEFT JOIN task_categories c ON t.category_id = c.id
      WHERE t.id = ? AND t.user_id = ?
    `;
    const tasks = await query(sql, [id, userId]);
    return tasks.length ? tasks[0] : null;
  },

  /**
   * 创建新任务
   * @param {Object} taskData - 任务数据
   * @returns {Promise<Object>} 创建的任务
   */
  create: async (taskData) => {
    const sql = `
      INSERT INTO tasks 
      (title, description, user_id, category_id, status, priority, 
       start_time, end_time, reminder_time, reminder_before, repeat_type, estimated_pomodoros) 
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `;
    
    const result = await query(sql, [
      taskData.title,
      taskData.description || null,
      taskData.user_id,
      taskData.category_id || null,
      taskData.status || 0,
      taskData.priority || 0,
      taskData.start_time || null,
      taskData.end_time || null,
      taskData.reminder_time || null,
      taskData.reminder_before || null,
      taskData.repeat_type || null,
      taskData.estimated_pomodoros || null
    ]);
    
    return { id: result.insertId, ...taskData };
  },

  /**
   * 更新任务
   * @param {number} id - 任务ID
   * @param {number} userId - 用户ID
   * @param {Object} updateData - 要更新的字段
   * @returns {Promise<boolean>} 更新是否成功
   */
  update: async (id, userId, updateData) => {
    const allowedFields = [
      'title', 'description', 'category_id', 'status', 'priority',
      'start_time', 'end_time', 'reminder_time', 'reminder_before', 
      'repeat_type', 'estimated_pomodoros'
    ];
    
    const fields = [];
    const values = [];

    // 构建动态更新SQL
    for (const field of allowedFields) {
      if (updateData[field] !== undefined) {
        fields.push(`${field} = ?`);
        values.push(updateData[field]);
      }
    }

    if (fields.length === 0) return false;

    values.push(id, userId);
    const sql = `UPDATE tasks SET ${fields.join(', ')} WHERE id = ? AND user_id = ?`;
    const result = await query(sql, values);
    
    return result.affectedRows > 0;
  },

  /**
   * 删除任务
   * @param {number} id - 任务ID
   * @param {number} userId - 用户ID
   * @returns {Promise<boolean>} 删除是否成功
   */
  delete: async (id, userId) => {
    const sql = 'DELETE FROM tasks WHERE id = ? AND user_id = ?';
    const result = await query(sql, [id, userId]);
    return result.affectedRows > 0;
  },

  /**
   * 获取任务分类列表
   * @param {number} userId - 用户ID
   * @returns {Promise<Array>} 分类列表
   */
  getCategories: async (userId) => {
    const sql = `
      SELECT * FROM task_categories 
      WHERE user_id = ? OR user_id IS NULL
      ORDER BY name
    `;
    return await query(sql, [userId]);
  },

  /**
   * 创建任务分类
   * @param {Object} categoryData - 分类数据
   * @returns {Promise<Object>} 创建的分类
   */
  createCategory: async (categoryData) => {
    const sql = 'INSERT INTO task_categories (name, color, icon, user_id) VALUES (?, ?, ?, ?)';
    const result = await query(sql, [
      categoryData.name,
      categoryData.color || null,
      categoryData.icon || null,
      categoryData.user_id
    ]);
    
    return { id: result.insertId, ...categoryData };
  }
};

module.exports = taskModel; 